from answer_question import get_answer

from flask import Flask, jsonify, request, abort
import uuid

app = Flask(__name__)

# 模拟聊天会话数据
chat_sessions = {}


@app.route('/start_chat', methods=['POST'])
def start_chat():
    # data = request.get_json()
    # user_id = data.get('user_id')
    user_id = str(uuid.uuid4())
    if user_id:
        chat_id = str(uuid.uuid4())
        chat_sessions[chat_id] = {
            "user_id": user_id,
            "messages": []
        }
        return jsonify({"chat_sessions": chat_sessions[chat_id]})
    return jsonify({"errCode": "chat_start_failed", "message": "未能成功开启倾诉聊天会话，请稍后重试。"}), 200


@app.route('/send_message', methods=['POST'])
def send_message():
    # 从 POST 请求体中获取 'question' 参数
    question = request.json.get('question')

    if question is None:
        abort(400, description="缺少问题参数，请提供问题")

    # 调用 answer_question.py 中的 get_answer 函数获取答案
    answer = get_answer(question)

    # 检查 answer 是否为 None
    if answer is None:
        return jsonify({"errCode": "no_data", "message": "这个问题无法回答"}), 404

    return jsonify({"answer": answer})


@app.route('/end_chat', methods=['POST'])
def end_chat():
    # data = request.get_json()
    # chat_id = data.get('chat_id')
    # if chat_id in chat_sessions:
    #     del chat_sessions[chat_id]
    #     return jsonify({"message": "倾诉聊天会话已成功结束。"})
    # return jsonify({"errCode": "chat_end_failed", "message": "未能成功结束聊天会话，请检查会话 ID 或稍后重试。"}), 200
    return jsonify({"message": "倾诉聊天会话已成功结束。"})


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=4999)